import { entryInfoUrl, entrySaveUrl, userInfoUrl, userUpdateeInfoUrl } from '../../../../api/individual'
import { post, uploadFile, initUploadFileListKey } from '../../../../utils/index'
import WxValidate from '../../../../utils/WxValidate'

Page({
  data: {
    page: '',
    readonly: false,
    form: { medicalReportFileList: [] },
    formError: {}
  },
  async submit () { // 保存信息
    const { form, page } = this.data
    if (!this.WxValidate.checkForm(form) || !form.medicalReportFileList.length) {
      const formError = this.WxValidate.formError
      if (!form.medicalReportFileList.length) {
        formError.medicalReportFileList = '请上传体检报告个人页'
      }
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    form.health = form.health ? '0' : '1'
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    await post(url, form)
    wx.navigateBack({})
  },
  async loadData () { // 获取人员信息
    const url = this.data.page === 'entry' ? entryInfoUrl : userInfoUrl
    const { data } = await post(url)
    data.medicalReportFileList.forEach(item => {
      item = initUploadFileListKey(item)
    })
    data.health = data.health === '0'
    this.setData({ form: data })
  },
  healthChange ({ detail }) { // 身体状况
    if (this.data.readonly) {
      return
    }
    this.setData({ 'form.health': detail })
  },
  async afterRead ({ detail }) { // 上传成功后
    const { file } = detail
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    const { medicalReportFileList } = this.data.form
    medicalReportFileList.push(data)
    this.setData({
      'form.medicalReportFileList': medicalReportFileList
    })
  },
  del ({ detail }) { // 删除
    const { index } = detail
    const { medicalReportFileList } = this.data.form
    medicalReportFileList.splice(index, 1)
    this.setData({
      'form.medicalReportFileList': medicalReportFileList
    })
  },
  preview ({ detail }) { // 预览
    const { index } = detail
    const file = this.data.form.medicalReportFileList[index]
    if (!file || file.isImage) {
      return
    }
    wx.openDocument({ filePath: file.url })
  },
  initValidator () { // 初始化验证器
    const rules = {
      health: { required: true }
    }
    const messages = {
      health: { required: '请选择健康状况' }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  readonlyChange () { // 编辑资料
    this.setData({ readonly: false })
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    const readonly = page === 'me'
    this.setData({ readonly, page })
    this.loadData()
    this.initValidator()
  }
})